package com.ml4ai.core.stack.utils;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * Created by leecheng on 2018/11/29.
 */
public class GsonUtil {

    public static GsonBuilder builder() {
        return new GsonBuilder();
    }

    public static String getFieldAsString(JsonObject json, String key) {
        if (json.get(key) == null) {
            return null;
        } else if (json.get(key).isJsonNull()) {
            return null;
        } else if (json.get(key).isJsonPrimitive()) {
            return json.get(key).getAsString();
        } else {
            return builder().create().toJson(json.get(key));
        }
    }

    public static Integer getFieldAsInt(JsonObject json, String key) {
        if (json.get(key) == null) {
            return null;
        } else if (json.get(key).isJsonNull()) {
            return null;
        } else if (json.get(key).isJsonPrimitive()) {
            String numberString = json.get(key).getAsString();
            if (numberString.matches("\\d+")) {
                return Integer.valueOf(numberString);
            } else {
                throw new IllegalStateException(String.format("[%s]不是数字格式", numberString));
            }
        } else {
            throw new IllegalStateException(String.format("[%s]不是数字", builder().create().toJson(json.get(key))));
        }
    }

    public static JsonObject parse(String json) {
        return (new JsonParser()).parse(json).getAsJsonObject();
    }
}
